var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    isCateStyle: false,
    active: '1',
    status: 3,
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    Concern: "",
    apiType: "AllLivelist",
    liveBanner: [],
    // 是否显示面板指示点
    indicatorDots: true,
    // 方向
    vertical: false,
    // 是否自动切换
    autoplay: true,
    // 自动切换时间间隔
    interval: 4000,
    // 滑动动画时长
    duration: 300,
    Concern_activitys1: [],
    Concern_activitys2: [],
    live_search: "",
    colOneHeight: 0,
    colTwoHeight: 0,
    navlistData: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.CAT) {
      this.setData({
        isCateStyle: true
      })
    }
    this.getBanner();
    this.getLiveList();
    if (options.mid) {
      app._setMid(options.mid);
    }
    this.throttleFunc = this.debounce(function () {
      this.getLiveList();
    }, 500);
  },
  //去首页
  gotoIndex(){
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  //自定义图标跳转
  intbtn(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url:"/mircoApp/share-room/list/list?CAT=" + id
    });
  },
  searchbtn(e) {
    let val = e.detail.value;
    this.data.live_search = val;
  },
  initData(){
    this.data.isLoadMore = true;
    this.data.page = 1;
    this.data.total_page = 0;
    this.data.colOneHeight = 0;
    this.data.colTwoHeight = 0;
    this.setData({
      Concern: [],
      Concern_activitys1: [],
      Concern_activitys2: [],
    });
  },
  searchConfirm() {
    this.initData();
    this.getLiveList();
  },

  chunk(arr, n) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i += n) {
      result.push(arr.slice(i, i + n));
    }
    return result;
  },
  getBanner() {
    let urlStr = app.getNetAddresss("plugin.share-room.frontend.controllers.index.index");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let category = res.data.category ? res.data.category : [];
          let category_10 = this.chunk(category, 10);
          this.setData({
            liveBanner: res.data.slide,
            navlistData: category_10,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  goUrl(e) {
    let url = e.currentTarget.dataset.url;
    if (url) {
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误:" + url,
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
 
  getLiveList(type) {
    wx.showLoading({
      title: '加载中',
    })
    this.initData();
    let urlStr = app.getNetAddresss(
      "plugin.share-room.frontend.controllers.index.room-list"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        category_id: this.options.CAT||0,
        status: Number(this.data.active) >= 0 ? this.data.active : '' ,
        is_recommend: Number(this.data.active) == '-1' ? 1 : '',
        keyword: this.data.live_search,
      },
      success: (resdata) => {
        var res = resdata.data;
        wx.hideLoading()
        if (res.result == 1) {
          this.setData({
            total_page: res.data.list.last_page,
            Concern: res.data.list.data,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log(res.msg);
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: "/mircoApp/share-room/list/list",
    };
  },

  golistPage(e) {
    let status = e.currentTarget.dataset.status;
    let url = '/mircoApp/share-room/player/player';
    let RId = e.currentTarget.dataset.id;
    let CAT = this.options.CAT || 0;
    let STAT = Number(this.active) >= 0 ? this.active : '';
    let REC = Number(this.active) == '-1' ? 1 : '';
    if (Number(status) == 0) url = '/mircoApp/share-room/foreshow/foreshow'
    wx.navigateTo({
      url: `${url}?RId=${RId}&CAT=${CAT}&STAT=${STAT}&REC=${REC}`
    });
  },
  //获取更多数据
  _getMoreData() {
    const that = this;
    let json = {};
    let api = "";
    let urlStr = "";
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      api = "plugin.share-room.frontend.controllers.index.room-list";
      json = {
        category_id: this.options.CAT||0,
        status: Number(this.data.active) >= 0 ? this.data.active : '' ,
        is_recommend: Number(this.data.active) == '-1' ? 1 : '',
        page: this.data.page,
      };
      json.keyword = this.data.live_search;
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              isLoadMore: true,
              Concern: that.data.Concern.concat(res.data.data),
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log("没有更多数据");
    }
  },
  swichTabTItem(e) {
    let name = e.detail.name;
    this.data.active = name;
    this.setData({
      live_search: "",
      Concern: [],
      Concern_activitys1: [],
      Concern_activitys2: []
    });
    
    this.throttleFunc();
  },
  

  debounce(func, wait) {
    console.log('ddddddddddd')
    let timeout;
    return function () {
      const context = this;
      const args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        func.apply(context, args);
      }, wait);
    };
  },


  onImageError(options) {
    let index = options.target.dataset.index;
    let seltype = options.target.dataset.seltype;
    // let currentId = options.currentTarget.id;
    console.log("图片加载发生错误");
    this.onImageLoad({
      target: {
        dataset: {
          index: index,
          seltype: seltype,
        },
      },
      detail: {
        width: 2340,
        height: 1080,
      },
    });
  },
  /**
   * 图片加载函数
   * 图片加载完成后，根据图片的高度，依次往第一列和第二列中推入数据
   */
  onImageLoad(options) {
    let index = options.target.dataset.index;
    let seltype = options.target.dataset.seltype;
    let imageWidth = options.detail.width; // 图片宽度
    let imageHeight = options.detail.height; // 图片高度
    let activityObj = null;
    let scle = imageWidth / imageHeight;
    
    let activitys = this.data.Concern; // 获取所有的数据资源
    activityObj = activitys[index];
    let activitys1 = this.data.Concern_activitys1;
    let activitys2 = this.data.Concern_activitys2;
    if (this.data.colOneHeight <= this.data.colTwoHeight) {
      this.data.colOneHeight += 176 / scle + 60;
      activitys1.push(activityObj);
    } else {
      this.data.colTwoHeight += 176 / scle + 60;
      activitys2.push(activityObj);
    }
    this.setData({
      Concern_activitys1: activitys1,
      Concern_activitys2: activitys2,
    });
    
  },
});
